var app = angular.module("myApp", [function () {
    Array.prototype.remove = function (val) {
        var index = this.indexOf(val);
        if (index > -1) {
            this.splice(index, 1);
        }
    };
}]);

app.controller("myCon1", ["$scope", "$window", function ($scope, $window) {

    $scope.newItem = "";
    $scope.name = "Daniel";
    $scope.itemsList = $window.localStorage.getItem("itemsList") ? JSON.parse($window.localStorage.getItem("itemsList")) : [];
    //$scope.itemsList = [];

    $scope.btnInput = function (event) {
        //回车
        if (event.which == 13 && $scope.newItem.trim() != "") {
            var item = new Object();
            item.name = $scope.newItem.trim();
            $scope.itemsList.push(item);
            $scope.newItem = "";
            saveItemList();
        }
    };

    function saveItemList() {
        $window.localStorage.removeItem("itemsList")
        $window.localStorage.setItem("itemsList", angular.toJson($scope.itemsList));
    }

    $scope.itemDbClick = function (event, item) {
        item.edit = true;
        item.orign = angular.copy(item);
    }

    $scope.btnItemEdit = function (event, item) {
        //回车
        if (event.which == 13) {
            if (item.name.trim() != "") {
                item.orign = angular.copy(item);
            } else {
                item.name = item.orign.name;
            }
            item.edit = false;
            saveItemList();
        }
    };

    $scope.btnItemBlur = function (item) {
        if (item.name.trim() != "") {
            item.orign = angular.copy(item);
        } else {
            item.name = item.orign.name;
        }
        item.edit = false;
        saveItemList();
    };

    $scope.divDelete = function (item) {
        $scope.itemsList.remove(item);
        saveItemList();
    };

    $scope.divToggleFinish = function (item) {
        item.finished =   !item.finished;
        saveItemList();
    };
}]);